﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TFC;

namespace EngineAccessLayer.Impl
{
    public class EngineAccess : IAccessable
    {
        private bool engine0State;
        private bool engine1State;
        private double pin0Height;
        private double pin1Height;
        private USBHandler handler;

        public EngineAccess(short port)
        {
            handler = new USBHandler();
            if (handler.OpenCommunication(port))
            {
                handler.SendCommand("SET(CONNECTED)\r\n");
                engine0State = true;
                engine1State = true;
                pin0Height = 0.0;
                pin1Height = 0.0;
            }
        }

        public bool GetEngineState(int engineId)
        {
            if (engineId == 0) return engine0State;
            else return engine1State;
        }

        public void ChangeEngineState(int engineId)
        {
            if (engineId == 0) engine0State = !engine0State;
            else engine1State = !engine1State;
        }

        public double GetPinHeight(int engineId)
        {
            if (engineId == 0) return pin0Height;
            else return pin1Height;
        }

        public void SetPinHeight(int engineId, double height)
        {
            double numberOfSteps = 0.0;
            double stepsForCm = Global.StepsForCm;
            double tolerance = Global.Tolerance;
            int direction;
            double diff;

            //if (GetEngineState(engineId))
            //{
                diff = height - GetPinHeight(engineId);

                if (Math.Abs(diff) > tolerance)
                {
                    if (diff > 0) direction = 1;
                    else direction = 0;

                    numberOfSteps = Math.Abs(diff) * stepsForCm;

                    SendCommand(engineId, direction, numberOfSteps);

                    if (engineId == 0) pin0Height = height;
                    else pin1Height = height;
                }
            //}
        }

        public void Close()
        {
            if (handler.CloseCommunication())
            {
                engine0State = false;
                engine1State = false;
                SetPinHeight(0, 0);
                SetPinHeight(1, 0);
            }
        }

        private void SendCommand(int engineId, int direction, double numberOfSteps)
        {
            engineId += 1;
            string commandDirection = "SET(M" + engineId + "_DIRCW," + direction + ")\r\n";
            string commandSteps = "SET(M" + engineId + "STEPNR," + (int)numberOfSteps + ")\r\n";

            //Console.WriteLine(commandDirection);
            //Console.WriteLine(commandSteps);

            handler.SendCommand(commandDirection);
            handler.SendCommand(commandSteps);

        }
    }
}
